<template>
	<button
		class="bg-transparent p-0 border-none base-code app-text-react text-base font-semibold"
		:class="[{ count: countdown }, _disabled ? 'text-t-3 !cursor-not-allowed' : 'text-primary']"
		:disabled="_disabled"
		@click="onClick">
		{{
			countdown
				? `${$t('action.resendCode')}(${countdown}s)`
				: _retry
					? $t('action.resendCode')
					: $t('action.sendCode')
		}}
	</button>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { sendEmailCode } from '@/api/assistants'
import { useCountdown, useMessage } from '@/hooks'
import { getItem, isEmail, setItem, t } from '@/utils'

const props = defineProps({
	email: {
		type: String,
		required: true
	},
	disabled: {
		type: Boolean,
		default: false
	},
	retry: {
		type: Boolean,
		default: false
	},
	// 使用验证码的场景; 登录,注册,绑定,重置...
	scene: {
		type: String,
		default: ''
	}
})

const emits = defineEmits(['sendSuccess'])

const message = useMessage()
const { countdown, reset } = useCountdown()
const loading = ref(false)
const _retry = ref(false)

const sceneKey = computed(() => `verifyCode.${props.scene}.${props.email}`)
const _disabled = computed(
	() => props.disabled || loading.value || countdown.value > 0 || !validator().valid
)

const validator = () => {
	const value = props.email
	let msg = ''
	if (!isEmail(value)) {
		msg = 'register.emailRuleInvalid'
	}
	return { textT: msg, valid: !msg }
}

const getCountdownFn = () => {
	const endTime = getItem(sceneKey.value) || 0
	const remainingSeconds = Math.max(Number(((endTime - Date.now()) / 1000).toFixed()), 0)
	_retry.value = props.retry || remainingSeconds > 0
	reset(remainingSeconds)
}

const onClick = async () => {
	if (loading.value) return
	try {
		loading.value = true
		const { data } = await sendEmailCode({ email: props.email })
		message.success(t('tip.sendCodeSuccess'))
		setItem(sceneKey.value, data || Date.now() + 60000)
		getCountdownFn()
		emits('sendSuccess')
	} catch (error) {
		message.error(error)
	} finally {
		loading.value = false
	}
}

watch([() => props.email], () => getCountdownFn())

onMounted(() => {
	if (props.retry) setItem(sceneKey.value, Date.now() + 60000)
	getCountdownFn()
})

defineExpose({ onClick })
</script>

<style scoped></style>
